﻿using Microsoft.SharePoint;
using System;
using System.Globalization;

namespace SP.Exporters.Extractors
{
    public class FieldDateTimeExtractor :IFieldValueExtractor
    {
        public SPField Field { get; set; }
        public string Format { get; set; }
        public FieldDateTimeExtractor(SPField field,string format)
        {
            Field = field;
            Format = format;
        }

        /// <summary>
        /// Gets the field value and applies the datetime format to it.
        /// </summary>
        /// <param name="item">The item.</param>
        /// <returns></returns>
        public string GetFieldValue(SPListItem item)
        {
            var dateTimeField = Field as SPFieldDateTime;
            if (dateTimeField == null)
            {
                throw new ExporterException("This is not a DateTime Field. ----- Field name: " + Field.Title);
            }
            var dateTime = item[Field.Id] as DateTime?;
            return dateTime.HasValue && !String.IsNullOrEmpty(Format)
                       ? dateTime.Value.ToString(Format, CultureInfo.CurrentUICulture)
                       : dateTimeField.GetFieldValueAsText(item[Field.Id]);
        }
    }
}
